#!/usr/bin/env python
# encoding: utf-8
"""
LatticeParser.py

Created by Pablo Ortega Mesa on 2011-01-28.
Copyright (c) 2011 Toeska Research Group. All rights reserved.
"""

import sys
import os

class Lattice():
	def __init__(self,lattice):
		self.lattice = lattice
		self.readLattice()
	def readLattice(self):
		f = open(self.lattice,"r")
		__lineN = 3
		counter = 0
		nodos = []
		nodo = {}
		for line in f:
			if not (line.startswith("#") or line.startswith("Top") or line.startswith("Bottom") or line.startswith("\n") or "generators" in line):
				counter += 1
				if counter%__lineN==1: #terms, docs stability and level information
					terms = line[line.index("[")+1:line.index("]")]
					nodo["terms"] = terms.split(", ")
					docs = line[line.index("{")+1:line.index("}")]
					nodo["docs"] = docs.split(", ")
					id = line[line.index("id=")+3:line.index("type")].replace(", ","")
					nodo["id"] = id
					lev = line[line.index("level=")+6:line.index("stability")].replace(", ","")
					nodo["level"] = lev
					stab = line[line.rfind("=")+1:]
					stab = float(stab.replace("]\n",""))
					nodo["stability"] = stab
				if counter%__lineN==2: #parents
					parent = line[line.index("[")+1:line.index("]")]
					parent = parent.split("}, ")
					padres = []
					for c in range(len(parent)):
						par = parent[c].replace("{","").replace("}","").strip()
						if par == "":
							padres.append("none")
						else:
							padres.append(par)
					if padres:
						nodo["parents"] = padres
				if counter%__lineN==0: #childrens
					children = line[line.index("[")+1:line.index("]")]
					children = children.split("}, ")
					hijos = []
					for c in range(len(children)):
						hij = children[c].replace("{","").replace("}","").strip()
						if hij == "":
							hijos.append("none")
						else:
							hijos.append(hij)
					if hijos:
						nodo["childrens"] = hijos
					
					if (nodo["docs"][0]!='') and (nodo["terms"][0]!='') and nodo["level"] and nodo["stability"] and nodo["id"] and nodo["parents"] and nodo["childrens"]:
						nodos.append(nodo)
					nodo = {}
		self.nodos = nodos
		
	def writeSQL(self,filenameSQL,filenameTERMS):
		
		
	
	def writeJsonExhibit(self,filename):
		'''
		{
		   items: [
			   {   label:              "John Doe",
				   type:               "Person",
				   age:                36,
				   likes:              "Mary Smith",
				   "favorite-color":   [ "blue", "yellow" ]
			   },
			   {   label:              "Mary Smith",
				   type:               "Person",
				   "married-to":       "Joe Anderson",
				   job:                "Doctor",
				   worksAt:            "Boston General Hospital",
				   hobby:              [ "painting", "karate" ]
			   },
			   {   label:   "Boston General Hospital",
				   type:    "Place",
				   city:    "Boston"
			   }
		   ]
	   }
		'''
		cont = 0
		out = '{\n'
		out += '\titems: [\n'
		for n in self.nodos:
			cont += 1
			out += '\t\t{\n'
			out += '\t\t\tlabel:\t\t\"nodo '+str(n['id'])+'\",\n'
			out += '\t\t\ttype:\t\t\"node\",\n'
			out += '\t\t\tdocs:\t\t['
			for d in n['docs']:
				out += '\"'+d+'\", '
			out += '],\n'
			out += '\t\t\tterms:\t\t['
			for t in n['terms']:
				out += '\"'+t+'\", '
			out += '],\n'
			out += '\t\t\tlevel:\t\t\"'+n['level']+'\",\n'
			out += "\t\t\tstability:\t\"%+0.3f\",\n"%+n['stability']
			out += '\t\t\tparents:\t\t['
			for p in n['parents']:
				out += '\"'+p+'\", '
			out += '],\n'
			out += '\t\t\tchildrens:\t\t['
			for c in n['childrens'][0].split(", "):
				out += '\"'+c+'\", '
			out += '],\n'
			out += '\t\t},\n'
		out += '\t]\n'
		out += '}'
			
		#print out
		outFile = open(filename,'w')
		outFile.write(out)
		outFile.close()
		print str(cont)+" nodes writen"

		
		
	def showNodos(self):
		for n in self.nodos:
			print n
			print "-----"